package com.infore.airsupervise.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.infore.airsupervise.R;
import com.infore.airsupervise.bean.ProgressBean;
import com.infore.airsupervise.biz.LoaderFileBiz;
import com.infore.airsupervise.biz.impl.LoaderFileBizImpl;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.other.DownLoaderProgressHanlder;
import com.infore.airsupervise.ui.widget.ItemDecoration1px;
import com.infore.airsupervise.utils.FileUtil;
import com.infore.airsupervise.utils.ToastUtil;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;

/**
 * @features:
 * @author: WuTao
 * @date: 2017/5/10 09:31
 */
public class MissionFileShowFragment extends BaseFragment {
    @BindView(R.id.show_photo_recycler_view)
    RecyclerView recyclerView;

    private List<String> datas;
    private BaseQuickAdapter<String,BaseViewHolder> adapter;
    private LoaderFileBiz loaderFileBiz;


    public MissionFileShowFragment() {
    }

    @SuppressLint("ValidFragment")
    public MissionFileShowFragment(List<String> datas) {
        if(null != datas) {
            this.datas = datas;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_show_photo,container,false);
        unbinder = ButterKnife.bind(this,view);
        loaderFileBiz = new LoaderFileBizImpl(progressHanlder ,new ProgressBean());

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new ItemDecoration1px(getContext(),ItemDecoration1px.VERTICAL_LIST));
        adapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_file,datas) {
            @Override
            protected void convert(BaseViewHolder helper, String item) {
                String fileName = item.substring(item.lastIndexOf("/")+1);
                helper.setText(R.id.tv_file_name,fileName);
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                String fileName = datas.get(position);
                fileName = fileName.substring(fileName.lastIndexOf("/")+1);
                File file = new File(Environment.getExternalStorageDirectory()+"/DCIM/AirSupervise/loader/"+fileName);
                if(file.exists()){
                    FileUtil.intentOpenFile(getContext(),file.getAbsolutePath(),
                            FileUtil.getFileMIMEType(fileName.substring(fileName.lastIndexOf(".")+1)));
                }else {

                    initProgressDialog(fileName);
                    Call call = loaderFileBiz.loaderFileRequest(fileName, new OnServerResponseListener<String>() {
                        @Override
                        public void onSucceed(String result, String desc) {

                        }

                        @Override
                        public void onFailed(int errorCode, String title, String desc) {
                            ToastUtil.showShort(getContext(),title +"，"+ desc);
                            setLoaderFailedUI(title,desc);
                        }

                    });
                    requests.add(call);
                }
            }
        });
        return view;
    }

    private  ProgressBar progressBar;
    private TextView tv_failed;
    private Button btn_cancel , btn_open;

    /**
     * 创建一个下载文件的提示框
     * @param fileName
     */
    private void initProgressDialog(final String fileName){
        SimpleDialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight){
                @Override
                protected void onBuildDone(final Dialog dialog) {
                    dialog.layoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    progressBar = (ProgressBar) dialog.findViewById(R.id.progressBar);
                    tv_failed = (TextView) dialog.findViewById(R.id.tv_failed_desc);
                    btn_cancel = (Button) dialog.findViewById(R.id.btn_cancel);
                    btn_open = (Button) dialog.findViewById(R.id.btn_open);
                    btn_cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                    btn_open.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            FileUtil.intentOpenFile(getContext(), Environment.getExternalStorageDirectory()+"/DCIM/AirSupervise/loader/"+fileName,
                                    FileUtil.getFileMIMEType(fileName.substring(fileName.lastIndexOf(".") + 1)));
                            dialog.dismiss();
                        }
                    });
                }
            };
            builder.contentView(R.layout.layout_progress)
            .title("下载进度");
        DialogFragment fragment = DialogFragment.newInstance(builder);
        fragment.setCancelable(false);
        fragment.show(getFragmentManager(), null);
    }

    /**
     * 实例化一个下载进度handler 用来操作UI
     */
    private DownLoaderProgressHanlder progressHanlder = new DownLoaderProgressHanlder() {
        @Override
        protected void onProgress(long progress, long total, boolean done) {
            Log.e("是否在主线程中运行", String.valueOf(Looper.getMainLooper() == Looper.myLooper()));
            Log.e("onProgress",String.format("%d%% done\n",(100 * progress) / total));
            Log.e("done","--->" + String.valueOf(done));
            setLoaderSuccessUI(progress,total,done);
        }
    };


    /**
     * 下载成功后 UI操作
     * @param progress
     * @param total
     * @param isFinish
     */
    private void setLoaderSuccessUI(final long progress, final long total, boolean isFinish){
        int pro = (int) (progress*100/total);
        progressBar.setProgress(pro);
        if(isFinish){
         btn_open.setVisibility(View.VISIBLE);
            btn_cancel.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 下载失败后UI操作
     * @param title
     * @param desc
     */
    private void setLoaderFailedUI(String title, String desc){
        tv_failed.setText(title + "," + desc);
        tv_failed.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
        btn_open.setVisibility(View.GONE);
        btn_cancel.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(loaderFileBiz != null){
            loaderFileBiz = null ;
        }
    }
}
